/**
 * 售后事件管理相关js文件
 */
/**
 * 页面初期化
 */

var eventTable; // datatble
var tblCheckOrder;
var tebType = false;
var quickSearch = ""; // 快速查询
var btnAdvSearchflg = false; // 高级查询是否点击标识
var searchCondition = {
		"queryDateType" : "",
		"queryDateStart" : "",
		"queryDateEnd" : ""
}; 

var tableData = {};

//高级查询
$(document).ready(function() {
    // 输入有效性验证
    $("#flagCreateForm , #flagEditForm").validate({
        debug:true,
        errorPlacement: function(error, element)
        {
            error.insertAfter(element);
        }
    });
    
    $.extend($.validator.defaults,{ignore:""}); //隐藏控件也校验，去掉此行不验证隐藏控件   
	initDataTable();// 列表数据请求
});

/*var SELECTORS = {
		EDIT_MODAL: "#edit-brand-form"
};
var brandEditionModal = $(SELECTORS.EDIT_MODAL);*/

//初始化teb数据条数
function getCounts() {

	$.ajax({
		type : "GET",
		url : "/afterSale/queryStateCount.action",
		data : {
			"quickSearch" : quickSearch,
			"formJson" : encodeURI(JSON.stringify(searchCondition))
		},
		contentType : "application/json;charset=utf-8",
		dataType : "json",
		async : true,// 同步
		success : function(data) {
			if (data.result == "success") {
				$("#finishNum").html(data.countComplete);
				$("#processingNum").html(data.countProcessing);
				$("#waitingNum").html(data.countPending);
				// $("#waitingNum3").html(data.countCancal);

			} else {
				window.top.window.showModalAlert(data.msg);
			}
		},
		error : function(XMLHttpRequest, textStatus) {
			if (XMLHttpRequest.status == 500) {
				var result = eval("(" + XMLHttpRequest.responseText + ")");
				alert(result.errorObject.errorText);
			}
		}
	});
	// quickSearch = "";
};

//初始化补发单表格（默认待审核）
function initDataTable() {
	if (!$.fn.DataTable.isDataTable('#brandListTable')) {
//		var loading = window.top.window.getIndexBusyOverlay();
		eventTable = $("#brandListTable").DataTable({
			"processing" : true,
			"serverSide" : true,
			"lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100, 500, 1000 ] ],
			"dom" : '<"bottom"rtflp>',
			"searching" : false,
			"scrollCollapse" : false,
			"bPaginate" : true, // 是否显示（应用）分页器
			"bInfo" : true, // 是否显示页脚信息，DataTables插件左下角显示记录数
			"pagingType" : "full_numbers",
			"deferRender" : true,
			"ajax" : {
				"url" : "/brand/getBrandList.action",
				"dataFilter": function(data) {
					var json = jQuery.parseJSON(data);
					tableData = json.data.reduce(function(a, b) {
						a[b.brandId] = b;
						return a;
					}, {});
					return JSON.stringify(json);
				},
				"data" : function(d) {
					d.quickSearch = quickSearch;
				}
			},
			"tableTools" : {
				"sRowSelect" : "bootstrap"
			},
//			"columnDefs" : [ {
//			"className" : "truncate-text tooltip-column-detail",
//			"targets" : [ 0 ]
//			}, {
//			"className" : "truncate-text tooltip-column-detail",
//			"targets" : [ 1 ]
//			}, {
//			"className" : "truncate-text tooltip-column-detail",
//			"targets" : [ 2 ]
//			}, {
//			"className" : "truncate-text tooltip-column-detail",
//			"targets" : [ 3 ]
//			}, {
//			"className" : "truncate-text tooltip-column-detail",
//			"targets" : [ 4 ]
//			}, {"targets": 5,//添加操作栏
//			"data": null,//下面这行，添加了编辑按钮和，删除按钮
//			"defaultContent": "<button id='operationEdit' type='button' class='btn btn-info btn-xs' style='margin-right:10px;'><i class='fa fa-edit'>编辑</i></button>" +
//			"<button id='operationDelete' class='btn btn-danger btn-xs' type='button'><i class='fa fa-trash-o'>删除</i></button>"
//			}],
			"columns" : [ {
				"data" : "brandCode",
				"orderable" : false
			}, {
				"data" : "brandName",
				"orderable" : false
			}, {
				"data" : "createTime"
			}, {
				"data" : "updateTime"
			}, {
				"data" : "remark",
				"orderable" : false
			}, { 
				"orderable" : false,
				"mRender": function(data, type, row) {
				return '<button data-id="' + row.brandId + '" type="button" class="btn btn-info btn-xs btn-brand-edit"><i class="fa fa fa-edit"></i>修改</button> \
				<button data-id="' + row.brandId + '" type="button" class="btn btn-danger btn-xs btn-brand-delete"><i class="fa fa-trash-o"></i>删除</button>'
			}}],
			"order" : [ [ 3, "desc" ] ]
		});
	} else {
		var optionData = eventTable.settings()[0].ajax.data;

		optionData = function(d) {
			d.quickSearch = quickSearch;
		}

		eventTable.settings()[0].ajax.data = optionData;
		eventTable.ajax.reload();
	}

	$("#brandListTable").tooltip({
		selector : ".tooltip-column-detail",
		container : "body",
		title : function() {
			if ($(this)[0].scrollWidth > $(this).outerWidth()) {
				return $(this).text();
			}
		}
	});
	
	// 删除品牌
	$("#brandListTable").on("click", ".btn-brand-delete", function() {
		var id = $(this).data("id"), data = tableData[id];
        window.top.window.showModalConfirm("确定要删除品牌吗？", function() {
        	var loading = window.top.window.getIndexBusyOverlay();
        	$.ajax({
                type:"POST",
                url:"/brand/deleteBrand.action?brandId=" + id,
                contentType: "application/json;charset=utf-8",
                dataType: "json",
//                async: false,//同步
                beforeSend:function(){
                    if(loading) {
                    	loading.settext("正在处理中，请稍后...");
                    }
                },
                success:function(data) {
                	loading.remove();
                	if (data.success == "Y") {
                        window.top.window.showScoMessage('ok', '删除成功');
                        eventTable.draw();
                    } else{
                        window.top.window.showModalAlert(data.errormessage);
                    }
                },
                error:function(XMLHttpRequest, textStatus) {
                	loading.remove();
                    if (XMLHttpRequest.status == 500) {
                        var result = eval("(" + XMLHttpRequest.responseText + ")");
                        alert(result.errorObject.errorText);
                    }
                }
            });
        });
	});
	
	// 添加按钮
	// 创建品牌保存按钮点击事件绑定
	$("#add-brand").click(function(){

		// 父窗体归还本页的编辑对话框
		window.top.window.returnCustomModalDialog();

		// 输入有效性验证
		if(!$("#brandCreateForm").valid()) {
			// 父窗体借用本页的编辑对话框
			window.top.window.borrowCustomModalDialog($("#create-brand-form"));
			return false;
		}
		//创建品牌
		var brandCode = $("#form-brand-code").val();
		var brandName = $("#form-brand-name").val();
		var remark = $("#form-remark").val()

		var params = {};  
		params.brandCode = brandCode;  
		params.brandName = brandName;
		params.remark = remark;
		var loading = window.top.window.getIndexBusyOverlay();
		$.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";
	    $.ajax({
	        type: "POST",
	        url:"/brand/createBrand.action",
	        data: JSON.stringify(params),
	        contentType: "application/json;charset=utf-8",
	        dataType: "json",
	        beforeSend:function(){
	            if(loading) {
	            	loading.settext("正在处理中，请稍后...");
	            }
	        },
	        success:function(data) {
	        	loading.remove();
				if (data.success == "Y") {
					$('#create-brand-form').modal('hide');
					window.top.window.showScoMessage('ok', '创建成功');
					eventTable.draw();
				} else{
					window.top.window.showModalAlert(data.errormessage);
					window.top.window.borrowCustomModalDialog($("#create-brand-form"));
				}
			},
			error:function(XMLHttpRequest, textStatus) {
				loading.remove();
				if (XMLHttpRequest.status == 500) {
					var result = eval("(" + XMLHttpRequest.responseText + ")");
					alert(result.errorObject.errorText);
				}
			}
	    });
	});

	// 创建分单规则保存按钮点击事件绑定
	$("#edit-brand").click(function(){

		// 父窗体归还本页的编辑对话框
		window.top.window.returnCustomModalDialog();

		// 输入有效性验证
		if(!$("#brandEditForm").valid()) {
			// 父窗体借用本页的编辑对话框
			window.top.window.borrowCustomModalDialog($("#edit-brand-form"));
			return false;
		}
		//保存品牌规则
		var brandId = $("#edit-brand-form").attr("brandId");
		var brandCode = $("#form-brand-codeEdit").val();
		var brandName = $("#form-brand-nameEdit").val();
		var remark = $("#form-remarkEdit").val();

		var params = {};  
		params.brandCode = brandCode;  
		params.brandName = brandName;
		params.brandId = brandId;
		params.remark = remark;
		$.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";
		var loading = window.top.window.getIndexBusyOverlay();
	    $.ajax({
	        type: "POST",
	        url:"/brand/updateBrand.action",
	        data: JSON.stringify(params),
	        contentType: "application/json;charset=utf-8",
	        dataType: "json",
	        beforeSend:function(){
	            if(loading) {
	            	loading.settext("正在处理中，请稍后...");
	            }
	        },
	        success:function(data) {
	        	loading.remove();
				if (data.success == "Y") {
					$('#edit-brand-form').modal('hide');
					window.top.window.showScoMessage('ok', '修改成功');
					eventTable.draw();
				} else{
					window.top.window.showModalAlert(data.errormessage);
					window.top.window.borrowCustomModalDialog($("#edit-brand-form"));
				}
			},
			error:function(XMLHttpRequest, textStatus) {
				loading.remove();
				if (XMLHttpRequest.status == 500) {
					var result = eval("(" + XMLHttpRequest.responseText + ")");
					alert(result.errorObject.errorText);
				}
			}
	    });
	});

	// 创建品牌对话框关闭事件发生
	$('#create-brand-form').on('hide.bs.modal', function () {
		// 父窗体归还本页的编辑对话框
		window.top.window.returnCustomModalDialog();
	});
	
	// 创建品牌规则对话框关闭事件发生
	$('#edit-brand-form').on('hide.bs.modal', function () {
		// 父窗体归还本页的编辑对话框
		window.top.window.returnCustomModalDialog();
	});
	
	// 品牌编辑事件
	$("#brandListTable").on("click", ".btn-brand-edit", function() {
		$("#brandEditForm")[0].reset();
		var id = $(this).data("id"), data = tableData[id];
		// 初始化项目列表
		$.ajax({
			type:"GET",
			url:"/brand/brandDetail.action?brandId=" + id,
			contentType: "application/json;charset=utf-8",
			dataType: "json",
			async: false,//同步
			success:function(data) {
				if (data.result == "success") {
					$("#edit-brand-form").attr("brandId", id);
					$("#form-brand-codeEdit").val(data.data.brandCode);
					$("#form-brand-nameEdit").val(data.data.brandName);
					$("#form-remarkEdit").val(data.data.remark);
					// 父窗体借用本页的编辑对话框
					var editDialog = window.top.window.borrowCustomModalDialog($("#edit-brand-form"));
					editDialog.modal({show:true, backdrop:'static'});
				} else{
					window.top.window.showScoMessage('ok', data.errormessage);
				}
			},
			error:function(XMLHttpRequest, textStatus) {
				if (XMLHttpRequest.status == 500) {
					var result = eval("(" + XMLHttpRequest.responseText + ")");
					alert(result.errorObject.errorText);
				}
			}
		});
	})
};

//刷新

$("#btnRefreshEvent").on('click', function() {
	quickSearch = "";
	$('#quickSearch').val("");
	initDataTable();
})
/*
 * 快速查询
 */
$("#btnQuickSearch").click(function() {
	quickSearch = encodeURI($('#quickSearch').val());
	initDataTable();
});

/**
 * 搜索框的回车事件
 */
$('#quickSearch').keydown(function(e) {
	if (e.keyCode == 13 && $('#btnQuickSearch').is(":visible")) {
		$("#btnQuickSearch").click();
	}
});

//下载
$("#downloadBrand").click(function () {
	$.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";
	$.ajax({
		type: "POST",
		url: "/brand/downLoadBrand.action",
		contentType: "application/json;charset=utf-8",
		dataType: "json",
		success: function (data) {
			if (data.success == "y") {
				window.top.window.showScoMessage('ok', '下载成功');
				eventTable.draw();
			} else {
				window.top.window.showModalAlert(data.msg);
			}
		},
		error: function (XMLHttpRequest, textStatus) {
			if (XMLHttpRequest.status == 500) {
				var result = eval("(" + XMLHttpRequest.responseText + ")");
				alert(result.errorObject.errorText);
			}
		}
	});
});

/**
 * 通用方法
 */
//初始化下拉控件
var initSelect = function(domElement) {
	$('.selectpicker', domElement).selectpicker();
};

/**
 * 打开创建的对话框
 * @returns
 */
function newBrand() {
	$("#brandCreateForm")[0].reset();

	var editDialog = window.top.window.borrowCustomModalDialog($("#create-brand-form"));
	editDialog.modal({show:true, backdrop:'static'});
}

